package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.domain.TbArea;
import com.bwie.domain.TbRepair;
import com.bwie.domain.TbRepairImage;
import com.bwie.domain.TbType;
import com.bwie.mapper.RepairMapper;
import com.bwie.mapper.TbAreaMapper;
import com.bwie.mapper.TbRepairImageMapper;
import com.bwie.mapper.TbTypeMapper;
import com.bwie.service.IUserService;
import com.bwie.service.RepairService;
import com.bwie.utils.R;
import com.bwie.vo.DataListVo;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/11/5 9:02
 */

@Service
public class RepairServiceImpl implements RepairService {

    @Autowired
    RepairMapper repairMapper;

    @Autowired
    TbTypeMapper typeMapper;

    @Autowired
    TbRepairImageMapper tbRepairImageMapper;

    @Autowired
    TbAreaMapper tbAreaMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    IUserService iUserService;

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Override
    public R getRepairCountByWeek() {
        // 查询数据
        List<DataListVo> list = repairMapper.getRepairCountByWeek();

        // 返回数据
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<String> xData = new ArrayList<>();
        ArrayList<Double> yData = new ArrayList<>();

        for (DataListVo dataListVo : list) {
            xData.add(dataListVo.getName());
            yData.add(dataListVo.getValue());
        }

        map.put("xData", xData);
        map.put("yData", yData);
        return R.OK(map);
    }

    @Override
    public R getRepairStatusByMonth() {

        // 查询正在维修的数据
        List<DataListVo> list1 = repairMapper.getRepairStatusByMonth(0);

        // 查询已经维修完成的数据
        List<DataListVo> list2 = repairMapper.getRepairStatusByMonth(1);

        // 返回数据
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Double> yData1 = new ArrayList<>();
        ArrayList<Double> yData2 = new ArrayList<>();
        ArrayList<String> xData = new ArrayList<>();

        for (DataListVo dataListVo : list1) {
            xData.add(dataListVo.getName());
            yData1.add(dataListVo.getValue());
        }

        for (DataListVo dataListVo : list2) {
            yData2.add(dataListVo.getValue());
        }

        map.put("xData", xData);
        map.put("yData1", yData1);  // 正在维修
        map.put("yData2", yData2);  // 已经维修完成

        return R.OK(map);
    }

    @Override
    public R getRepairStatusByArea() {
// 查询正在维修的数据
        List<DataListVo> list1 = repairMapper.getRepairStatusByArea(0);

        // 查询已经维修完成的数据
        List<DataListVo> list2 = repairMapper.getRepairStatusByArea(1);

        // 返回数据
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Double> yData1 = new ArrayList<>();
        ArrayList<Double> yData2 = new ArrayList<>();
        ArrayList<String> xData = new ArrayList<>();

        for (DataListVo dataListVo : list1) {
            xData.add(dataListVo.getName());
            yData1.add(dataListVo.getValue());
        }

        for (DataListVo dataListVo : list2) {
            yData2.add(dataListVo.getValue());
        }

        map.put("xData", xData);
        map.put("yData1", yData1);  // 正在维修
        map.put("yData2", yData2);  // 已经维修完成

        return R.OK(map);
    }

    @Override
    public R getRepairList(PageInfoVo pageInfoVo) {

        // 查询列表
        Page<TbRepair> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TbRepair> tbRepairPage = null;

        // 获取用户角色信息
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "用户未登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        R r = iUserService.getUserById(userId);
        if(r.getCode() != 200) {
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        if(JSON.parseObject(s).getInteger("userRole") == 1) {
            // 管理员：userId=null,则查询所有的信息
            tbRepairPage = repairMapper.getRepairList(page, null, pageInfoVo.getKeyWord(), pageInfoVo.getTypeId(), pageInfoVo.getStatus());
        }
        else {
            // 普通用户
            tbRepairPage = repairMapper.getRepairList(page, userId, pageInfoVo.getKeyWord(), pageInfoVo.getTypeId(), pageInfoVo.getStatus());
        }

        return R.OK(tbRepairPage);
    }

    @Override
    public R getTypeList() {

        List<TbType> tbTypes = typeMapper.selectList(null);
        return R.OK(tbTypes);
    }

    @Override
    public R uploadFile(MultipartFile file) {

        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String fullPath = storePath.getFullPath();
            String url = "http://192.168.80.192:8888/" + fullPath;

            return R.OK(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ERROR(500, "上传失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addRepair(TbRepair tbRepair) {
        //-- 添加报修单
        tbRepair.setCreateTime(new Date());
        tbRepair.setRepairNo(""+System.currentTimeMillis());
        tbRepair.setRepairStatus(0);

        repairMapper.insert(tbRepair);

        //-- 添加报修单的图片
        List<String> imageList = tbRepair.getImageList();
        if(imageList != null && imageList.size()>0) {
            for (String imageUrl : imageList) {
                TbRepairImage tbRepairImage = new TbRepairImage();
                tbRepairImage.setRepairId(tbRepair.getRepairId());
                tbRepairImage.setImageUrl(imageUrl);
                tbRepairImageMapper.insert(tbRepairImage);
            }
        }

        return R.OK();
    }

    @Override
    public R getAreaList() {
        List<TbArea> areaList = tbAreaMapper.selectList(null);
        return R.OK(areaList);
    }

}
